﻿@page "/client/login"
@inject HttpClient Http
@inject Blazored.LocalStorage.ISyncLocalStorageService localStorage
@inject NavigationManager NavigationManager
@inject NotificationService ns

<div class="row">
    <div class="col-md-12">
        <RadzenTemplateForm TItem="Model" Data="@model" Submit="@OnSubmit">
            <RadzenFieldset Text="请登录">
                <div class="row" style="margin-bottom: 48px">
                    <div class="col-md-4 align-right">
                        <RadzenLabel Text="用户名" />
                    </div>
                    <div class="col">
                        <RadzenTextBox style="display: block" Name="FirstName" @bind-Value="model.Itcode" />
                    </div>
                </div>
                <div class="row" style="margin-bottom: 48px">
                    <div class="col-md-4">
                        <RadzenLabel Text="密码" />
                    </div>
                    <div class="col">
                        <RadzenPassword  style="display: block" Name="LastName" @bind-Value="model.Password" />
                    </div>
                </div>
                <RadzenButton ButtonType="ButtonType.Submit" Text="登录"></RadzenButton>
            </RadzenFieldset>
        </RadzenTemplateForm>
    </div>
</div>
@code {
    class Model
    {
        public string Itcode { get; set; }
        public string Password { get; set; }
    }


    Model model = new Model();


    async Task OnSubmit(Model model)
    {

        var content = new FormUrlEncodedContent(new[] {
                    new KeyValuePair<string, string>("userid", model.Itcode),
                    new KeyValuePair<string, string>("password", model.Password),
                    new KeyValuePair<string, string>("cookie", "false")
                    });
        var res = await Http.PostAsync("/api/_Account/Login", content);
        if (res.IsSuccessStatusCode == true)
        {
            var jwt = JsonSerializer.Deserialize<Token>(await res.Content.ReadAsStringAsync());
            localStorage.SetItem("token", jwt.access_token);
            localStorage.SetItem("rtoken", jwt.refresh_token);
            NavigationManager.NavigateTo("/client/");
        }
        else
        {
            ns.Notify(new NotificationMessage() { Severity = NotificationSeverity.Error, Summary = "错误", Detail = "登录失败", Duration = 4000 });
            return;
        }
    }

}